﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using Quartz;
using User.Api.HttpClients;  

namespace Out.TaskRunner.QuartzJobs
{
    public class TransferDeptAndDoctorInfoJob: IJob
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(TransferDeptAndDoctorInfoJob));

        /// <summary>
        /// 执行成功
        /// </summary>
        public bool IsExecuteSuccess = true;

        /// <summary>
        /// 重试次数
        /// </summary>
        public int RetryTimes = 0;

        public void Execute(IJobExecutionContext context)
        {
            Logger.InfoFormat("Executing job: {0}", context.JobDetail.Key);

            DoTransferDeptAndDoctorInfo();

            while (true)
            {
                if (RetryTimes > 5)
                {
                    IsExecuteSuccess = true;
                    RetryTimes = 0;
                    break;
                }
                
                if (!IsExecuteSuccess)
                {
                    DoTransferDeptAndDoctorInfo();
                }

                RetryTimes++;
            }
        }

        public void DoTransferDeptAndDoctorInfo()
        {
            Console.WriteLine("[{0}] 获取科室和医生信息", DateTime.Now.ToString("MM-dd HH:mm:ss"));

            var deptList = new List<string>();
            var hospitalId = "0";
            var respDept = GetDeptGroupInHosp();
            if (respDept.ResultCode == "0")
            {
                foreach (var resp in respDept.DeptList)
                {
                    var response4GetDeptInfo = GetDeptsInHosp(resp.DeptId);
                    if (response4GetDeptInfo.ResultCode == "0")
                    {
                        foreach (var deptInfoInHosp in response4GetDeptInfo.DeptList)
                        {
                            SaveDept(hospitalId, "0", deptInfoInHosp);//没有分院，默认0
                            deptList.Add(deptInfoInHosp.DeptId);

                            var response4GetDoctorInfo = GetDoctorsInHosp(deptInfoInHosp.DeptId);
                            if (response4GetDoctorInfo.ResultCode == "0")
                            {
                                foreach (var doctorInfoInHosp in response4GetDoctorInfo.DoctorList)
                                {
                                    SaveDoctor(hospitalId, "0", doctorInfoInHosp);//没有分院，默认0
                                }
                                //保存医生信息
                                using (var ctx = new HzfyWeiXinEntities())
                                {
                                    //判断医生是否在院内存在

                                    var doctors = ctx.Doctor.Where(x => x.DeptId == deptInfoInHosp.DeptId && x.RecStatus == 1);
                                    foreach (var doctor in doctors)
                                    {
                                        //RecStatus=2  表示不在院内
                                        if (!response4GetDoctorInfo.DoctorList.Any(x => x.DoctorId == doctor.DoctorId))
                                        {
                                            doctor.RecStatus = 2;
                                            doctor.RecDeleteDt = DateTime.Now;
                                        }
                                    }
                                    ctx.SaveChanges();
                                }
                            }
                            else
                            {
                                IsExecuteSuccess = false;
                            }
                        }
                    }
                    else
                    {
                        IsExecuteSuccess = false;
                    }
                }
            }
            else
            {
                IsExecuteSuccess = false;
            }

            if (IsExecuteSuccess)
            {
                //判断科室是否在院内存在
                using (var ctx = new HzfyWeiXinEntities())
                {
                    var depts = ctx.Depart.Where(x => x.RecStatus == 1);
                    foreach (var dept in depts)
                    {
                        if (!deptList.Any(x => x == dept.DeptId))
                        {
                            dept.RecStatus = 2;
                            dept.RecDeleteDt = DateTime.Now;
                        }
                    }
                    ctx.SaveChanges();
                }
                Console.WriteLine("[{0}] 成功获取科室和医生信息", DateTime.Now.ToString("MM-dd HH:mm:ss"));
            }
            
        }



        public bool SaveDept(string hospitalId, string branch, GetDeptInfoResponse.DeptInfo deptInfoInHosp)
        {
            using (var ctx = new HzfyWeiXinEntities())
            {
                var deptQuery = ctx.Depart.Where(x => x.DeptId == deptInfoInHosp.DeptId);
                if (deptQuery.Any())
                {
                    var dept = deptQuery.First();
                    dept.DeptId = deptInfoInHosp.DeptId;
                    dept.BranchNo = branch;
                    dept.DeptName = deptInfoInHosp.DeptName;
                    //dept.Desc = deptInfoInHosp.Desc;
                    dept.Loc = deptInfoInHosp.Loc;
                    dept.RecStatus = 1;
                    dept.HospId = 1;
                    dept.ParentId = "-1";
                    ctx.SaveChanges();
                }
                else
                {
                    var dept = new Depart();
                    dept.DeptId = deptInfoInHosp.DeptId;
                    dept.BranchNo = branch;
                    dept.DeptName = deptInfoInHosp.DeptName;
                   // dept.Desc = deptInfoInHosp.Desc;
                    dept.Loc = deptInfoInHosp.Loc;
                    dept.RecStatus = 1;
                    dept.HospId = 1;
                    dept.RecCreateDt = DateTime.Now;
                    dept.ParentId = "-1";
                    ctx.Depart.Add(dept);
                    ctx.SaveChanges();
                }
            }
            return true;
        }

        public bool SaveDoctor(string hospitalId, string branch, GetDoctorInfoResponse.DoctorInfo doctorInfoInHosp)
        {
            using (var ctx = new HzfyWeiXinEntities())
            {
                var dept = ctx.Depart.FirstOrDefault(x => x.DeptId == doctorInfoInHosp.DeptId);
                var deptName = dept?.DeptName;
                var doctorQuery = ctx.Doctor.Where(x => x.DoctorId == doctorInfoInHosp.DoctorId && x.DeptId == doctorInfoInHosp.DeptId);
                if (doctorQuery.Any()) //更新 
                {
                    var doctor = doctorQuery.First();
                    doctor.BranchNo = branch;
                    doctor.DeptId = doctorInfoInHosp.DeptId;
                    doctor.DepartName = deptName;
                    //doctor.Desc = doctorInfoInHosp.Desc;
                    doctor.DoctorId = doctorInfoInHosp.DoctorId;
                    doctor.DoctorName = doctorInfoInHosp.DoctorName;
                    //doctor.Fee = doctorInfoInHosp.Fee;
                    //doctor.Gender = doctorInfoInHosp.Gender;
                    doctor.HospId = 1;
                    doctor.RecStatus = 1;
                    doctor.Title = doctorInfoInHosp.Title;
                    ctx.SaveChanges();
                }
                else
                {
                    var doctor = new Doctor();
                    doctor.BranchNo = branch;
                    doctor.DeptId = doctorInfoInHosp.DeptId;
                    doctor.DepartName = deptName;
                    //doctor.Desc = doctorInfoInHosp.Desc;
                    doctor.DoctorId = doctorInfoInHosp.DoctorId;
                    doctor.DoctorName = doctorInfoInHosp.DoctorName;
                    //doctor.Fee = doctorInfoInHosp.Fee;
                    //doctor.Gender = doctorInfoInHosp.Gender;
                    doctor.HospId = 1;
                    doctor.Title = doctorInfoInHosp.Title;
                    doctor.RecStatus = 1;
                    doctor.RecCreateDt = DateTime.Now;
                    ctx.Doctor.Add(doctor);
                    ctx.SaveChanges();
                }
            }
            return true;
        }

        /// <summary>
        /// 一级排班
        /// </summary>
        /// <param name="hospitalId"></param>
        /// <returns></returns>
        public GetDeptInfoResponse GetDeptGroupInHosp()
        {
            var request = new GetDeptInfoRequest();

            GetDeptInfoResponse response4GetDeptInfo;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetDeptGroupInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response4GetDeptInfo = responseMsg.Content.ReadAsAsync<GetDeptInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("GetDeptGroupInfo Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return null;
            }

            return response4GetDeptInfo;
        }
        public GetDeptInfoResponse GetDeptsInHosp(string deptId)
        {
            var request = new GetDeptInfoRequest();
            request.DeptId = deptId;

            GetDeptInfoResponse response4GetDeptInfo;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetDeptInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response4GetDeptInfo = responseMsg.Content.ReadAsAsync<GetDeptInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("GetDeptInfo Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return null;
            }
            return response4GetDeptInfo;
        }
                

        public GetDoctorInfoResponse GetDoctorsInHosp(string deptId)
        {
            var request = new GetDoctorInfoRequest();
            request.DeptId = deptId;
            request.DoctorId = "";

            GetDoctorInfoResponse response4GetDoctorInfo;

            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetDoctorInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response4GetDoctorInfo = responseMsg.Content.ReadAsAsync<GetDoctorInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内GetDoctorInfo Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return null;
            }

            return response4GetDoctorInfo;
        }
    }
}
